package com.youhome.service.impl;

import com.aliyun.oss.OSSClient;
import com.youhome.config.Constant;
import com.youhome.config.OSSConfig;
import com.youhome.utils.FileUtil;
import com.youhome.utils.OSSUtil;
import com.youhome.service.UploadService;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.UUID;

/**
 * Created by chen365 on 2017/10/20.
 */

@Service
public class UploadServiceImpl implements UploadService {
    private static Logger logger = Logger.getLogger(OSSUtil.class);

    @Autowired
    private OSSConfig ossConfig;


    @Override
    public String upload(String base64Data) throws Exception {

        String[] datas = base64Data.split("base64,");
        String data = "";
        String prefix = null;
        if (datas != null && datas.length == 2) {
            prefix = datas[0];
            data = datas[1];
        } else {
            throw new Exception("请选择图片");
        }

        String suffix = "";
        if ("data:image/jpeg;".equalsIgnoreCase(prefix)) {
            suffix = ".jpg";
        } else if ("data:image/x-icon;".equalsIgnoreCase(prefix)) {
            suffix = ".ico";
        } else if ("data:image/gif;".equalsIgnoreCase(prefix)) {
            suffix = ".gif";
        } else if ("data:image/png;".equalsIgnoreCase(prefix)) {
            suffix = ".png";
        } else {
            throw new Exception("上传图片格式不合法");
        }

        String filename = UUID.randomUUID().toString() + suffix;
        OSSClient ossClient = new OSSClient(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
        String md5key = OSSUtil.uploadObject2OSS(ossClient, data, filename, ossConfig.getBacketName());
        logger.info("上传后的文件MD5数字唯一签名:" + md5key);

        return ossConfig.getDomain() + filename;
    }

    @Override
    public String upload(String base64Data, String ext) throws Exception {

        String[] datas = base64Data.split("base64,");
        String data = "";
        String prefix = null;
        if (datas != null && datas.length == 2) {
            prefix = datas[0];
            data = datas[1];
        } else {
            throw new Exception("请选择图片");
        }

        String suffix = "";

        if ("data:image/jpeg;".equalsIgnoreCase(prefix)) {
            suffix = "jpg";
        } else if ("data:image/jpg;".equalsIgnoreCase(prefix)) {
            suffix = "jpg";
        } else if ("data:image/png;".equalsIgnoreCase(prefix)) {
            suffix = "png";
        }
        System.err.println("ext:" + ext + "==" + suffix);
        if (!ext.equalsIgnoreCase(suffix)) {
            throw new Exception("图片格式不正确，不允许传" + ext);
        }
        byte[] bytes = new BASE64Decoder().decodeBuffer(data);
        String filename = UUID.randomUUID().toString() + "." + suffix;
        OSSClient ossClient = new OSSClient(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
        String md5key = OSSUtil.uploadObject2OSS(ossClient, bytes, filename, ossConfig.getBacketName(), "photo/");
        logger.info("上传后的文件MD5数字唯一签名:" + md5key);

        return ossConfig.getDomain() + "/photo/" + filename;
    }


    @Override
    public String uploadMailPhoto(File file) {
        try {
            OSSClient ossClient = new OSSClient(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
            String md5key = OSSUtil.uploadObject2OSS(ossClient, file, ossConfig.getBacketName(), "mail");
            logger.info("上传后的文件MD5数字唯一签名:" + md5key);
            FileUtils.deleteQuietly(file);
            String imageUrl = ossConfig.getDomain() + "mail/" + file.getName();
            // 返回"图像信息"选项卡并显示图片 ,在对应的文本框中显示图片资源url
            return imageUrl;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void uploadExcel(String path) throws Exception {
        System.err.println("Excel开始上传oss。。。");
        try {
            File file = new File(path);
            if (file.exists()) {
                OSSClient ossClient = new OSSClient(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
                // 设置bucket权限
                //ossClient.setBucketAcl(ossConfig.getReportBacketName(), CannedAccessControlList.Private);
                String md5key = OSSUtil.uploadObject2OSS(ossClient, file, ossConfig.getBacketName(), "excel");
                //logger.info("上传后的文件MD5数字唯一签名:" + md5key);
                System.err.println("Excel已经上传oss。。。");
                ossClient.shutdown();
                FileUtil.deleteFile(path); //上传成功后删除文件
            } else {
                System.err.println("文件不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String upload(File file) {
        try {
            OSSClient ossClient = new OSSClient(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
            String md5key = OSSUtil.uploadObject2OSS(ossClient, file, ossConfig.getBacketName(), "upload");
            logger.info("上传后的文件MD5数字唯一签名:" + md5key);
            FileUtils.deleteQuietly(file);
            String imageUrl = ossConfig.getDomain() + "upload/" + file.getName();
            // 返回"图像信息"选项卡并显示图片 ,在对应的文本框中显示图片资源url
            return imageUrl;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String upload(MultipartFile file) {
        try {
            String originalFileName = file.getOriginalFilename();
            String ext = originalFileName.substring(originalFileName.lastIndexOf("."), originalFileName.length()).toLowerCase();
            String newFileName = UUID.randomUUID().toString() + ext;
            String uploadPath = Constant.PIC_HOUSE_LOCATION;
            File file2 = new File(uploadPath, newFileName);
            FileUtils.copyInputStreamToFile(file.getInputStream(), file2);

            OSSClient ossClient = new OSSClient(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
            String md5key = OSSUtil.uploadObject2OSS(ossClient, file2, ossConfig.getBacketName(), "upload");
            logger.info("上传后的文件MD5数字唯一签名:" + md5key);
            FileUtils.deleteQuietly(file2);
            String imageUrl = "upload/" + newFileName;
            // 返回"图像信息"选项卡并显示图片 ,在对应的文本框中显示图片资源url
            return imageUrl;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String upload(MultipartFile file, Integer type) {

        String folder;
        if (type == 1) {
            folder = "upload";
        } else if (type == 2) {
            folder = "photo";
        } else if (type == 3) {
            folder = "house";
        } else {
            folder = "upload";
        }
        try {
            String originalFileName = file.getOriginalFilename();
            String ext = originalFileName.substring(originalFileName.lastIndexOf("."), originalFileName.length()).toLowerCase();
            String newFileName = UUID.randomUUID().toString() + ext;
            String uploadPath = Constant.PIC_HOUSE_LOCATION;
            File file2 = new File(uploadPath, newFileName);
            FileUtils.copyInputStreamToFile(file.getInputStream(), file2);

            OSSClient ossClient = new OSSClient(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
            String md5key = OSSUtil.uploadObject2OSS(ossClient, file2, ossConfig.getBacketName(), folder);
            logger.info("上传后的文件MD5数字唯一签名:" + md5key);
            FileUtils.deleteQuietly(file2);
            String imageUrl = folder + "/" + newFileName;
            // 返回"图像信息"选项卡并显示图片 ,在对应的文本框中显示图片资源url
            return imageUrl;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
